package cn.wx.fileclient.factory;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * Created by IntelliJ IDEA.
 * cn.wx.fileclient.factory
 * name：MybatisSqlSessionFactory
 * user：pengpeng
 * date:2020/11/2
 * time:12:46
 */
@Slf4j
public class MybatisSqlSessionFactory {
    // 单例模式(饿汉式)
    private static SqlSessionFactory sqlSessionFactory;
    static {
        //读取配置文件
        try(InputStream is= Resources.getResourceAsStream("mybatis-config.xml")) {
            //初始化mybatis，创建SqlSessionFactory类实例
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        } catch (IOException e) {
            log.error("load mybatis-config.xml fail! {}",e.getMessage());
        }
    }

    /**
     * 获取一个sqlSession
     * @return
     */
    public static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession();
    }

}
